import { PluginOption } from "@scmt/cli";
import { createMdPlugin } from "../markdown";

async function markdownToVue(source: string) {
  const md = await createMdPlugin();
  const templateString = md.render(source);

  return `<template><div class="vp-doc">${templateString}</div></template>`;
}

export default function MarkdownVitePlugin(): PluginOption {
  return {
    name: "markdown-vite-plugin",
    enforce: "pre",
    async transform(source, id) {
      if (/\.md$/.test(id)) {
        return await markdownToVue(source);
      }
    },
    async handleHotUpdate(ctx) {
      if (!/\.md$/.test(ctx.file)) return;

      const readSource = ctx.read;

      ctx.read = async function () {
        return await markdownToVue(await readSource());
      };
    },
  };
}
